<template>
  <div class="approver">
    <div
      v-if="route.query.name === '1' && props.readonly"
      class="approver-details"
    >
      <div
        v-for="(item, index) in detailsList"
        :key="index"
        class="approver-item"
      >
        <div class="approver-item-c">
          <el-avatar :src="url + item.avatar"></el-avatar>
          <el-tag
            type="success"
            :closable="route.query.name !== '3'"
            @close="handleDelOpportunitiesApprover(index)"
          >
            {{ item.approvalName }}
          </el-tag>
        </div>
        <div v-if="!isCc && index !== detailsList.length - 1">
          <el-icon><Right /></el-icon>
        </div>
      </div>
    </div>

    <div v-else-if="route.query.name === '1'" class="approver-add">
      <div class="approver-item" v-for="(item, index) in approver" :key="index">
        <div class="approver-item-c">
          <el-avatar :src="url + item.avatar"></el-avatar>
          <el-tag
            type="success"
            :closable="userStore.userId !== item.userId"
            @close="handleDelOpportunitiesApprover(index)"
          >
            {{ item.approvalName || item.nickName }}
          </el-tag>
        </div>
        <div v-if="!isCc && index !== approver.length - 1">
          <el-icon><Right /></el-icon>
        </div>

        <template
          v-if="
            !isCc &&
            typeof item.state === 'number' &&
            item.state !== 0 &&
            !isEdit
          "
        >
          <div>{{ item.byTheDate }}</div>
          <div>审批意见：{{ item.approvalOpinion }}</div>
        </template>
      </div>
    </div>

    <div v-else class="approver-details">
      <div
        v-for="(item, index) in detailsList"
        :key="index"
        class="approver-item"
      >
        <div class="approver-item-c">
          <el-avatar :src="url + item.avatar"></el-avatar>
          <el-tag
            type="success"
            :closable="route.query.name !== '3'"
            @close="handleDelOpportunitiesApprover(index)"
          >
            {{ item.username || item.approvalName }}
          </el-tag>
        </div>
        <div v-if="!isCc && index !== detailsList.length - 1">
          <el-icon><Right /></el-icon>
        </div>
      </div>
    </div>
    <div v-if="!readonly" class="head">
      <el-button
        link
        type="primary"
        round
        v-if="hasButtonSave && mark"
        @click="
          approverDialog = true;
          handleAddPeople();
        "
        style="position: relative; top: -3px; left: -10px"
      >
        {{ isCc ? "添加抄送人" : "添加审批人" }}
      </el-button>
      <el-button
        link
        type="primary"
        round
        v-if="!mark && hasButtonSave"
        @click="
          approverDialog = true;
          handleAddPeopleS();
        "
        style="position: relative; top: -3px; left: -10px"
      >
        {{ !flag ? "添加记录人员" : "添加参会人员" }}
      </el-button>
    </div>

    <!--  -->
    <el-dialog
      :title="addTitle"
      v-if="approverDialog"
      v-model="approverDialog"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handleClose"
      center
      width="90%"
    >
      <!-- 部门数据 -->
      <el-row :gutter="20">
        <!--部门数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input
              v-model="deptName"
              placeholder="请输入部门名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :expand-on-click-node="false"
              :props="{ label: 'label', children: 'children' }"
              :filter-node-method="filterNode"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="20" :xs="24">
          <el-form
            :model="queryParams"
            ref="queryRef"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="queryParams.nickName"
                placeholder="请输入用户昵称"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="table-wrapper">
            <el-table
              v-loading="loading"
              ref="userTable"
              :data="userList"
              @selection-change="handleChooseapprover"
            >
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column
                label="用户编号"
                align="center"
                key="userId"
                prop="userId"
                v-if="columns[0].visible"
              />
              <el-table-column
                label="用户名称"
                align="center"
                key="userName"
                prop="userName"
                v-if="columns[1].visible"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="用户昵称"
                align="center"
                key="nickName"
                prop="nickName"
                v-if="columns[2].visible"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="部门"
                align="center"
                key="deptName"
                prop="dept.deptName"
                v-if="columns[3].visible"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="手机号码"
                align="center"
                key="phonenumber"
                prop="phonenumber"
                v-if="columns[4].visible"
                width="120"
              />
              <el-table-column
                label="创建时间"
                align="center"
                prop="createTime"
                v-if="columns[6].visible"
                width="160"
              >
                <template #default="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <el-row type="flex" justify="end" style="margin-top: 10px">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryParams.pageNum"
              :page-size="queryParams.pageSize"
              :page-sizes="[9999999]"
              layout="total, prev, pager, next, sizes"
              :total="total"
            ></el-pagination>
          </el-row>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script setup>
import headerImg from "@/assets/images/default-header.png";
import { nextTick, onMounted, reactive, watch } from "vue";
import { Search } from "@element-plus/icons-vue";
import {
  selectsPeople,
  deptNameApi,
  selectsPeoples,
  deptTreeSelect,
  listUser,
} from "@/api/project/conversion";

import { useRouter, useRoute } from "vue-router";
import useUserStore from "@/store/modules/user";
const route = useRoute();

const stateNameArr = ["待审核", "审核通过", "审核驳回"];
const headerImgSrc = ref(headerImg);
const addTitle = ref("添加审批人");
const url = import.meta.env.VITE_APP_BASE_API;
const router = useRouter();

const userStore = useUserStore();

const groupParams = reactive({
  nickName: "", //员工姓名
  deptId: "", //所属部门
});
const groupList = ref([]);
const deptName = ref("");
const hasButtonSave = ref(false);
// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户名称`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true },
]);

// 1.按钮保存隐藏
const hasButton = () => {
  if (route.query.name === "3") {
    if (route.query.task === "2") {
      hasButtonSave.value = true;
    } else {
      hasButtonSave.value = false;
    }
  } else {
    hasButtonSave.value = true;
  }
};
const check = ref(true);

const userTable = ref();

const approverDialog = ref(false);

const dropdownList = ref([]);
// 所属部门名称
const deptNameRole = async () => {
  try {
    let params = {};
    const response = await deptNameApi(params);
    if (response.code === 200 && response.data.length >= 0) {
      dropdownList.value = response.data;
    }
  } catch (err) {
    console.log(err);
  }
};

const approver = ref([]);
let dropdownprops = {
  value: "deptId",
  label: "deptName",
  emitPath: false,
};

const props = defineProps({
  // 请求用户列表的函数
  getUserFn: {
    type: Function,
    default: () => {},
  },

  typeId: {
    default: undefined,
  },
  // 是否为抄送
  isCc: {
    type: Boolean,
    default: false,
  },
  // 角色按钮是否显示
  role: {
    type: Boolean,
    default: false,
  },
  // 回显的话为true
  readonly: {
    type: Boolean,
    default: false,
  },
  // 是否为编辑
  isEdit: {
    type: Boolean,
    default: false,
  },
  approverList: {
    type: Array,
    default: () => [],
  },
  flag: {
    type: Boolean,
    default: false,
  },
  mark: {
    type: Boolean,
    default: true,
  },
});

const handleAddPeople = async () => {
  await getList();
  if (props.isCc) {
    addTitle.value = "添加抄送人";
  } else {
    addTitle.value = "添加审批人";
  }
};
const handleAddPeopleS = async () => {
  await getList();
  if (props.flag) {
    addTitle.value = "添加参会人员";
  } else {
    addTitle.value = "添加记录人员";
  }
};
let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0);

const emit = defineEmits([
  "handleChooseapprover",
  "handleCancelapprover",
  "approverData",
]);
const deptOptions = ref(undefined);
const { proxy } = getCurrentInstance();
const userList = ref([]);
/** 根据名称筛选部门树 */
watch(deptName, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.deptId = data.id;
  handleQuery();
}

/** 搜索按钮操作 */
function handleQuery() {
  // debugger
  // queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  // dateRange.value = [];
  // proxy.resetForm("queryRef");
  queryParams.deptId = undefined;
  queryParams.nickName = "";
  // proxy.$refs.deptTreeRef.setCurrentKey(null);
  // handleQuery();
  // getList();
  queryParams.pageNum = 1;
  // console.log(cancelledRows,'---cancelledRows---')
  getList();
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}

const queryParams = reactive({
  pageNum: 1,
  pageSize: 9999999,
  nickName: undefined,
  phonenumber: undefined,
  status: undefined,
  deptId: undefined,
});

const detailsApprover = ref([]);
const detailsList = ref([]);

/** 查询用户列表 */
const getList = async () => {
  try {
    const response = await selectsPeoples(queryParams);
    if (response.code === 200 && response.rows.length >= 0) {
      userList.value = response.rows;

      total.value = response.total;
      // 在数据加载完成后，设置当前选择人
      setCurrentPerson();
      //有已选择数据：找到相同的数据，将已选择数据中的状态赋值给弹窗列表的状态
      if (route.query.name === "1") {
        if (approver.value.length) {
          // 找到相同的数据的数组
          const currentPage = queryParams.pageNum;
          // console.log(currentPage,'---123---')
          const savedSelections = selectionMap.get(currentPage) || [];

          // 清空 selectedRows 以避免旧数据干扰
          selectedRows.value = [];

          // if (!cancelApprover.value) {
          approver.value.forEach((item) => {
            const selectUser = userList.value.find(
              (it) => it.userId === item.userId
            );
            // @ts-ignore
            if (selectUser) {
              nextTick(() => {
                userTable.value?.toggleRowSelection(selectUser, true);
                selectedRows.value.push(selectUser); // 更新 selectedRows
              });
            }
          });
          // 恢复选择状态
        }
      } else {
        if (detailsList.value.length) {
          // 找到相同的数据的数组
          detailsList.value.forEach((item) => {
            const selectUser = userList.value.find(
              (it) => it.userId === item.userId
            );
            // @ts-ignore
            if (selectUser) {
              nextTick(() => {
                userTable.value.toggleRowSelection(selectUser, true);
              });
            }
          });
        }
      }
    }
  } catch (err) {
    console.log(err);
  }
};

watch(props.approverList, async (val) => {
  await getList();
});

const handleSizeChange = async (valueSise) => {
  queryParams.pageSize = valueSise;
  await getList();
};

const handleCurrentChange = async (valuePage) => {
  queryParams.pageNum = valuePage;
  await getList();
};

const selectedRows = ref([]); // 当前页面选中的行
const selectionMap = reactive(new Map()); // 持久化存储每页的选择

function handleChooseapprover(newSelection) {
  if (route.query.name === "1") {
    // 更新当前页面的选择状态
    const currentPage = queryParams.pageNum;
    selectionMap.set(currentPage, newSelection);
    // 获取当前页面的选择
    const currentSelection = newSelection;

    const prevSelection = selectedRows.value;

    const cancelledRows = prevSelection.filter((row) => {
      return !currentSelection.some(
        (selectedRow) => selectedRow.userId === row.userId
      );
    });

    // 如果有行被取消选择，进行处理
    if (cancelledRows.length > 0) {
      console.log("取消选择的行：", cancelledRows);

      // 移除 approver.value 中对应的审批者数据
      cancelledRows.forEach(async (cancelledRow) => {
        if (userStore.userId !== cancelledRow.userId) {
          const indexToRemove = approver.value.findIndex(
            (approverItem) => approverItem.userId === cancelledRow.userId
          );
          if (indexToRemove !== -1) {
            approver.value.splice(indexToRemove, 1); // 使用 splice 删除元素以保持响应性
          }
        }
      });

      // 如果需要重新计算审批级别，可以在这里调整
      approver.value.forEach((item, index) => {
        item.approvalLevel = index + 1;
      });
      // 默认的当前登陆人一直被选择
      approver.value.forEach((item) => {
        const selectUser = userList.value.find(
          (it) => it.userId === item.userId
        );
        // @ts-ignore
        if (selectUser) {
          nextTick(() => {
            userTable.value?.toggleRowSelection(selectUser, true);
            selectedRows.value.push(selectUser); // 更新 selectedRows
          });
        }
      });
    } else {
      console.log("没有取消选择的行");
    }
    // 获取新增加的选择项
    const addedRows = currentSelection.filter(
      (row) => !prevSelection.some((prevRow) => prevRow.userId === row.userId)
    );
    // 添加新的选择项到 approver.value
    addedRows.forEach((addedItem) => {
      // 检查是否已经存在相同的 userId 的审批者
      const existingApproverIndex = approver.value.findIndex(
        (item) => item.userId === addedItem.userId
      );

      if (existingApproverIndex === -1) {
        // 创建新的审批者对象并添加到 approver.value
        approver.value.push({
          approvalLevel: approver.value.length + 1,
          approvalName: addedItem.nickName || addedItem.approvalName,
          userId: addedItem.userId,
          avatar: addedItem.avatar,
        });
      }
    });

    // 更新 selectedRows 以备下一次比较使用
    selectedRows.value = [...currentSelection];

    // 根据路由查询参数决定发送哪个列表给父组件

    let userIds = approver.value.map((item) => item.userId);
    emit("handleChooseapprover", userIds);
  }
}

// 移除人员
const handleDelOpportunitiesApprover = async (index) => {
  if (route.query.name === "1") {
    approver.value.splice(index, 1);
    approver.value.forEach((item, i) => {
      item.approvalLevel = i + 1;
    });
  } else {
    const index = detailsList.value.findIndex((it) => it.userId === row.userId);
    detailsList.value.splice(index, 1);
    // 级别
    detailsList.value.forEach((item, i) => {
      item.approvalLevel = i + 1;
    });

    emit("handleCancelapprover");
  }
};

const cancelApprover = ref(true);

// 审批人取消
const handleCancelapprover = (row) => {
  cancelApprover.value = false;
  // 删除当前条数据
  if (route.query.name === "1") {
    const index = approver.value.findIndex((it) => it.userId === row.userId);
    approver.value.splice(index, 1);
  } else {
    const index = detailsList.value.findIndex((it) => it.userId === row.userId);
    console.log(index);
    // @ts-ignore
    detailsList.value.splice(index, 1);
  }

  emit("handleCancelapprover");
};

// 关闭
const handleClose = () => {
  approverDialog.value = false;
  queryParams.nickName = "";
};

// 监听变化
watchEffect(async () => {
  if (route.query.name === "1" && props.readonly) {
    detailsApprover.value = props.approverList;
  } else if (route.query.name === "1") {
    approver.value = props.approverList;
  } else {
    detailsApprover.value = props.approverList;
  }

  // 默认审批人列表数据
  detailsList.value = detailsApprover.value.map((item, index) => ({
    approvalLevel: index + 1,
    userId: Number(item.userId),
    approvalName: item.nickName || item.userName || item.approvalName,
    avatar: item.avatar,
  }));

  // console.log(detailsApprover.value,'---detailsApprover.value---')

  // getList();
});
const currentPerson = ref();

// 设置当前选择人
const setCurrentPerson = () => {
  currentPerson.value = userList.value.find(
    (it) => userStore.userId === it.userId
  );

  if (currentPerson.value) {
    nextTick(() => {
      // 确保表格已经渲染完成并且引用可用
      if (userTable.value) {
        userTable.value.toggleRowSelection(currentPerson.value, true);
      } else {
        // ElMessage.error("Table reference not found");
        // console.log("获取不到");
      }
    });
  }
};

onMounted(async () => {
  hasButton();
  await getList();
  await getDeptTree();

  // 默认当前选择人
});
// 暴露数据或方法给父组件
defineExpose({
  currentPerson,
});
</script>




<style lang="scss" scoped>
.approver {
  display: flex;
}
.table-wrapper {
  height: 500px; /* 设置你需要的高度 */
  overflow: auto;
}

.approver-add {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  // background: #fff;
  .approver-item {
    display: flex;
    justify-content: space-between;
    .approver-item-c {
      padding: 0 10px;
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      & > * {
        margin: 5px 0;
      }
    }
  }

  :deep(.el-form-item__content) {
    display: flex;
  }
}

.approver-details {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  .approver-item {
    display: flex;
    justify-content: space-between;
    .approver-item-c {
      padding: 0 10px;
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      & > * {
        margin: 5px 0;
      }
    }
  }

  :deep(.el-form-item__content) {
    display: flex;
  }
}
</style>
